/**
 * user服务实现
 *
 * @author sxf
 * @email sxf02615@163.com
 * @date 2025/1/15
 */
package com.sxf.crm.service.impl;


import com.sxf.crm.entity.User;
import com.sxf.crm.repository.UserRepository;
import com.sxf.crm.security.JwtTokenUtil;
import com.sxf.crm.service.UserService;
import com.sxf.crm.utils.SecurityUtils;

import lombok.RequiredArgsConstructor;

import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户服务实现类
 *
 * @author sxf
 * @email sxf02615@163.com
 * @date 2025/1/15
 */
@Service
@RequiredArgsConstructor
@Transactional
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    @Lazy
    private final AuthenticationManager authenticationManager;
    private final JwtTokenUtil jwtTokenUtil;

    @Override
    public String login(String username, String password) {
        // 进行身份验证
        Authentication authentication = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(username, password)
        );

        // 获取用户详情
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        
        // 更新最后登录时间
        User user = findByUsername(username);
        user.setLastLoginTime(System.currentTimeMillis());
        user.setUpdateAt(System.currentTimeMillis());
        user.setUpdateUserId(user.getId());
        userRepository.save(user);

        // 生成JWT token
        return jwtTokenUtil.generateToken(userDetails);
    }

    @Override
    public void logout(String token) {
        // 在实际应用中，你可能需要将token加入黑名单
        // 这里简单实现，实际项目中可能需要使用Redis等存储黑名单
        // TODO: 实现token黑名单机制
    }

    @Override
    public User createUser(String username, String password) {
        if (userRepository.findByUsername(username).isPresent()) {
            throw new RuntimeException("Username already exists");
        }

        User user = new User();
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(password));
        
        // 设置创建和更新信息
        Long currentUserId = SecurityUtils.getCurrentUserId();
        user.setCreateUserId(currentUserId);
        user.setUpdateUserId(currentUserId);
        user.setCreateAt(System.currentTimeMillis());
        user.setUpdateAt(System.currentTimeMillis());
        
        return userRepository.save(user);
    }

    @Override
    public User findByUsername(String username) {
        return userRepository.findByUsername(username)
                .orElseThrow(() -> new UsernameNotFoundException("User not found with username: " + username));
    }

    @Override
    public User updateUser(User user) {
        // 设置更新信息
        user.setUpdateUserId(SecurityUtils.getCurrentUserId());
        user.setUpdateAt(System.currentTimeMillis());
        return userRepository.save(user);
    }

    @Override
    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }

    @Override
    @Transactional(readOnly = true)
    public User getUserByUsername(String username) {
        return userRepository.findByUsername(username)
            .orElseThrow(() -> new RuntimeException("User not found with username: " + username));
    }

    @Override
    public User getUserById(Long ownerId) {
        if (ownerId == null) {
            return null;
        }
        return userRepository.findById(ownerId)
            .orElseThrow(() -> new RuntimeException("User not found with ID: " + ownerId));
    }
}